<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 科研机构信息 -->
          <div class="project-part">
            <div class="project-part-title">
              科研机构信息
            </div>

            <el-row>
              <el-col :span="6">
                <el-form-item label="高校名称" prop="name">
                  <el-input
                    v-model="basicForm.name"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="联系人及联系方式"
                  prop="contract"
                >
                  <el-input
                    v-model="basicForm.contract"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="机构介绍">
                  <el-input
                    v-model="basicForm.introduce"
                    placeholder="请输入"
                    type="textarea"
                    :rows="3"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 图片上传 -->
          <div class="project-part">
            <div class="project-part-title">图片上传</div>
            <el-form-item label="">
              <el-upload
                class="upload-image"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChangeImage"
                :on-remove="handleRemoveImage"
                :on-preview="handlePreviewImage"
                :show-file-list="true"
                :file-list="fileList"
                v-if="!isDetail"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"
                  ><div class="icon-text">上传图片</div></i
                >
                <div slot="tip" class="el-upload__tip">
                  支持格式：jpg、png，单个文件不能超过 5MB
                </div>
              </el-upload>

              <el-dialog
                :visible.sync="previewVisible"
                width="50%"
                v-if="!isDetail"
              >
                <img
                  :src="previewImage"
                  alt="预览"
                  style="width: 100%"
                />
              </el-dialog>
              <el-image
                v-for="item in fileList"
                :preview-src-list="previewImageList"
                v-if="isDetail"
                :key="item.url"
                :src="item.url"
                class="image"
              >
              </el-image>
            </el-form-item>
          </div>
        </el-form>

        <div class="project-part">
          <div class="project-part-title">高校人数</div>
          <!-- <span class="project-part-add"> -->
          <el-button
            icon="el-icon-plus"
            class="add-button"
            @click="addUniversity"
            v-if="
              yearList.length < yearOptions.length &&
              !isDetail
            "
            >新增</el-button
          >
          <!-- </span> -->
        </div>

        <el-table
          :data="yearList"
          class="year-table"
          :header-cell-style="{
            background: '#F2F6FB',
            color: ' #6B767D'
          }"
        >
          <el-table-column label="年度" prop="year">
            <template slot-scope="scope">
              <el-select
                placeholder="年度"
                v-model="scope.row.year"
                :disabled="isDetail"
              >
                <el-option
                  v-for="item in yearOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                  :disabled="
                    isOptionDisabledYear(item, scope.row)
                  "
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="人数(人)"
            prop="peopleCount"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.peopleCount"
                type="number"
                placeholder="请输入"
                :disabled="isDetail"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="请输入"
                :disabled="isDetail"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            v-if="!isDetail"
          >
            <template slot-scope="scope">
              <el-button
                @click="deleteUniversity(scope.$index)"
                type="text"
                style="color: #ff5b5b; font-weight: 400"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addUniversityCollaboration,
  queryUniversityCollaborationById,
  uploadFileById
} from '@/api/dataManagement'
import {
  scienceTypeOptions,
  scienceFieldOptions
} from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        name: '',
        contract: '',
        picture: '',
        introduce: '',
        yearRelList: []
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入科研中心名称',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      uploadFileList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: [],
      fileList: [],
      yearList: [],
      yearOptions: []
    }
  },
  created() {
    const currentYear = new Date().getFullYear()
    this.yearOptions = Array.from(
      { length: 3 },
      (_, i) => currentYear - 2 + i
    ).sort((a, b) => b - a)
  },
  computed: {
    titles() {
      return [this.title]
    },
    scienceTypeOptions() {
      return scienceTypeOptions
    },
    scienceFieldOptions() {
      return scienceFieldOptions
    }
  },
  watch: {},
  mounted() {
    if (this.pkid) {
      this.getDetail()
    }
  },
  methods: {
    getDetail() {
      queryUniversityCollaborationById(this.pkid).then(
        (res) => {
          this.basicForm = JSON.parse(
            JSON.stringify(res.data)
          )
          this.yearList = JSON.parse(
            JSON.stringify(res.data.yearRelList)
          )
          if (
            res.data.resourceFileInfos &&
            res.data.resourceFileInfos.length
          ) {
            this.fileList = res.data.resourceFileInfos.map(
              (item) => {
                return {
                  ...item,
                  url: `${STATIC_FILE_URL}${item.filePath}`
                }
              }
            )

            if (this.isDetail) {
              this.previewImageList = this.fileList.map(
                (item) => item.url
              )
            }

            this.uploadFileList = JSON.parse(
              JSON.stringify(this.fileList)
            )
          }
        }
      )
    },
    isOptionDisabledYear(optionValue, currentRow) {
      const selectedYears = this.yearList
        .filter((row) => row !== currentRow)
        .map((row) => row.year)
        .filter(Boolean)

      return selectedYears.includes(optionValue)
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJpgOrPng) {
        this.uploadFileList = this.uploadFileList.filter(
          (i) => i.name !== file.name
        )
        this.fileList = this.fileList.filter(
          (i) => i.name !== file.name
        )
        this.$message.error(
          '只能上传 JPG 或 PNG 格式的图片'
        )
        return
      }

      if (!isLt5M) {
        this.uploadFileList = this.uploadFileList.filter(
          (i) => i.name !== file.name
        )
        this.fileList = this.fileList.filter(
          (i) => i.name !== file.name
        )
        this.$message.error('图片大小不能超过 5MB')
        return
      }
    },

    addUniversity() {
      this.yearList.push({
        year: '',
        peopleCount: '',
        remark: ''
      })
    },

    deleteUniversity(index) {
      this.yearList.splice(index, 1)
    },

    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.beforeUpload(file.raw)
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          const currentUpload = this.uploadFileList.filter(
            (i) => !i.pkid
          )
          const isUploadImage = this.uploadFileList
            .filter((i) => i.pkid)
            .map((item) => item.pkid)

          const uploadPromises = currentUpload.map(
            (file) => {
              const image = new FormData()
              image.append('file', file)
              return uploadFileById(image)
            }
          )

          Promise.all(uploadPromises)
            .then((results) => {
              const allSuccess = results.every(
                (res) => res.success
              )

              if (!allSuccess) {
                this.$message.error('部分图片上传失败')
                return
              }

              let imageArr = results.map(
                (item) => item.data
              )
              this.basicForm.picture = imageArr
                .concat(isUploadImage)
                .join(',')
              this.basicForm.yearRelList = this.yearList
              // if (this.pkid) {
              //   this.basicForm.resourceFileInfos = null
              // }
              addUniversityCollaboration(
                this.basicForm
              ).then((res) => {
                if (res.success) {
                  this.$message.success(
                    this.pkid ? '编辑成功' : '保存成功'
                  )
                  this.$router.push({
                    path: '/dataManagement/technologyManagement/universityCollaboration/list',
                    query: { refresh: Date.now() }
                  })
                } else {
                  this.$message.error(res.message)
                }
              })
            })
            .catch((err) => {
              this.loading = false
              this.$message.error('图片上传出错')
              console.error(err)
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }

  .el-icon-plus {
    margin-top: 50px;
    .icon-text {
      color: #999;
      font-size: 16px;
      margin-top: 10px;
    }
  }
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}

.project {
  padding: 0 10px;

  &-part {
    position: relative;
    // display: flex;
    align-items: center;
    // margin-top: 20px !important;
    vertical-align: middle;
  }

  .el-table {
    margin: 20px 0;
  }

  &-title {
    display: inline-block;
    vertical-align: middle;
  }

  // &-add {

  //   margin-left: 12px;
  // }

  .add-button {
    display: inline-block;
    vertical-align: middle;
    position: absolute;
    left: 0;
    top: 0;
    width: 100px;
    height: 32px;
    background: #497fa3;
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
    margin-left: 150px;
    display: flex;
    align-items: center;
    margin-top: -8px;
  }
}
</style>
